package com.egg.basic.config.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.awt.*;

/**
 * 验证码配置
 *
 * @author east
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "security.captcha")
public class CaptchaConfig {


    @ApiModelProperty(value = "验证码开关", notes = "true=开启,false=关闭")
    private Boolean enabled;

    @ApiModelProperty(value = "验证码类型", notes = "com.egg.basic.enums.captcha.CaptchaTypeEnum")
    private String type;

    @ApiModelProperty(value = "验证码样式", notes = "com.egg.basic.enums.captcha.CaptchaStyleEnum")
    private String style;

    @ApiModelProperty(value = "有效期,单位秒", notes = "120")
    private Integer time;


    @Bean
    public CaptchaConfig initLoginCaptchaConfig() {
        CaptchaConfig captchaConfig = new CaptchaConfig();
        captchaConfig.setEnabled(getEnabled());
        captchaConfig.setType(getType());
        captchaConfig.setTime(getTime());
        log.info("初始化成功 {}", CaptchaConfig.class.getName());
        return captchaConfig;
    }


    /**
     * 数字计算验证码生成器
     *
     * @return
     */
    @Lazy
    @Bean
    public MathGenerator mathGenerator() {
        return new MathGenerator();
    }

    /**
     * 随机字符验证码生成器
     *
     * @return
     */
    @Lazy
    @Bean
    public RandomGenerator randomGenerator() {
        return new RandomGenerator(6);
    }

    private static final int WIDTH = 160;
    private static final int HEIGHT = 60;
    private static final Color BACKGROUND = Color.PINK;
    private static final Font FONT = new Font("Arial", Font.BOLD, 48);

    /**
     * 线段干扰的验证码
     */
    @Lazy
    @Bean
    public LineCaptcha lineCaptcha() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(WIDTH, HEIGHT);
        captcha.setBackground(BACKGROUND);
        captcha.setFont(FONT);
        return captcha;
    }

    /**
     * 圆圈干扰验证码
     */
    @Lazy
    @Bean
    public CircleCaptcha circleCaptcha() {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(WIDTH, HEIGHT);
        captcha.setBackground(BACKGROUND);
        captcha.setFont(FONT);
        return captcha;
    }

    /**
     * 扭曲干扰验证码
     */
    @Lazy
    @Bean
    public ShearCaptcha shearCaptcha() {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(WIDTH, HEIGHT);
        captcha.setBackground(BACKGROUND);
        captcha.setFont(FONT);
        return captcha;
    }


}